package com.tudouji.project.copy.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.tudouji.framework.config.KDConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.enums.DataType;
import com.tudouji.project.copy.domain.Copytokd;
import com.tudouji.project.copy.domain.Copytokditem;
import com.tudouji.project.copy.domain.Kdsynparamcomp;
import com.tudouji.project.copy.mapper.KdsynparamcompMapper;
import com.tudouji.project.system.service.ISysConfigService;

import _128._90._114._47.ormrpc.services.WSSCMWebServiceFacade.WSSCMWebServiceFacadeSrvProxy;
import _128._90._114._47.ormrpc.services.WSSCMWebServiceFacade.WSSCMWebServiceFacadeSrvProxyProxy;
import client.WSContext;

import org.apache.axis.client.Call;
import javax.xml.namespace.QName;

/**
 * 金蝶请求工具类
 * 
 * @author xiaxl
 *
 */
@Slf4j
@Service
public class KdPostUtils {

	@Autowired
	private KdsynparamcompMapper kdsynparamMapper;

	@Autowired
	private ISysConfigService sysConfigService;

	/**
	 * 请求
	 * 
	 * @param copy
	 * @param items
	 * @return
	 */
	public Map<String, String> post(Copytokd copy, List<Copytokditem> items) throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		String loginMsg=login();// 登录
//		if(StringUtils.isNotBlank(loginMsg)){
			WSSCMWebServiceFacadeSrvProxy scmSrvProxy = new WSSCMWebServiceFacadeSrvProxyProxy();
			String postJson = assembleDate(copy, items);
			log.debug(postJson);
			String resultMsg = scmSrvProxy.importBill(copy.getKdtype(), postJson, 1);
			JSONObject json = JSONObject.parseObject(resultMsg);
			log.debug("______________result________"+json.toJSONString());
			if(!json.get("status").toString().equals("0")){
				result.put("msg", json.get("billErrors").toString());
			}
			result.put("status", json.get("status").toString());
//		}else{
//			result.put("status", "2");
//			result.put("msg", "登录失败");
//		}
		return result;
	}

	public String login() {
		try {
			org.apache.axis.client.Service s = new org.apache.axis.client.Service();
			Call call = (Call) s.createCall();
			call.setOperationName("login");
			call.setTargetEndpointAddress(KDConfig.getKd_post_url());
			call.setReturnType(new QName("urn:client", "WSContext"));
			call.setReturnClass(WSContext.class);
			call.setReturnQName(new QName("", "loginReturn"));
			// 超时
			call.setTimeout(Integer.valueOf(1000 * 600000 * 60));
			call.setMaintainSession(true);
			log.info("Kd_user:{}",KDConfig.getKd_user());
			log.info("Kd_pwd:{}",KDConfig.getKd_pwd());
			log.info("Kd_data:{}",KDConfig.getKd_data());
			// 登陆接口参数
			WSContext rs = (WSContext) call.invoke(new Object[] { KDConfig.getKd_user(),
					KDConfig.getKd_pwd(), "eas", KDConfig.getKd_data(),
					"l2", Integer.valueOf(0) });
			return rs.getSessionId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 请求参数组装
	 * 
	 * @param copy
	 * @param items
	 * @return
	 */
	public String assembleDate(Copytokd copy, List<Copytokditem> items) {
		// 金蝶请求参数 为数组类型json字符串
		Set<Object> data = new HashSet<>();
		// 主表数据
		Map<String, Object> mainData = new HashMap<String, Object>();
		List<Kdsynparamcomp> params = kdsynparamMapper.selectKdsynparamcompList(new Kdsynparamcomp(copy.getKdtype(), 1));
		for (Kdsynparamcomp param : params) {
			if (StringUtils.isBlank(param.getDefaultValue())) {
				if (param.getType() == DataType.NUMBER.getCode()) {
					mainData.put(param.getKdParam(), new BigDecimal(copy.getValueByParam(param.getErpParam())));
				}else if (param.getType() == DataType.DATE.getCode()) {// 日期类型需要转换
					String date = dateFormat(copy.getValueByParam(param.getErpParam()));
					mainData.put(param.getKdParam(), date);
				}else if (param.getType() == DataType.BASEINFO.getCode()) {
					Map<String, Object> base = new HashMap<String, Object>();
					base.put("number", copy.getValueByParam(param.getErpParam()));
					mainData.put(param.getKdParam(), base);
				} else {
					mainData.put(param.getKdParam(), copy.getValueByParam(param.getErpParam()));
				}
			} else {
				if (param.getType() == DataType.NUMBER.getCode()) {
					mainData.put(param.getKdParam(), new BigDecimal(param.getDefaultValue()));
				}else if (param.getType() == DataType.BASEINFO.getCode()) {
					Map<String, Object> base = new HashMap<String, Object>();
					base.put("number", param.getDefaultValue());
					mainData.put(param.getKdParam(), base);
				} else {
					mainData.put(param.getKdParam(), param.getDefaultValue());
				}
			}
		}
		log.debug("+++++++++++++"+JSONObject.toJSONString(mainData).toString());
		// 组装明细数据
		List<Map<String, Object>> subs = new ArrayList<>();
		List<Kdsynparamcomp> itemParams = kdsynparamMapper.selectKdsynparamcompList(new Kdsynparamcomp(copy.getKdtype(), 2));
		log.info("items is null or not "+(items==null));
		for (Copytokditem item : items) {
			Map<String, Object> sub = new HashMap<String, Object>();
			for (Kdsynparamcomp param : itemParams) {
				if (StringUtils.isBlank(param.getDefaultValue())) {
					if (param.getType() == DataType.NUMBER.getCode()) {
						sub.put(param.getKdParam(), new BigDecimal(item.getValueByParam(param.getErpParam())));
					}else if (param.getType() == DataType.DATE.getCode()) {// 日期类型需要转换
						String date = dateFormat(item.getValueByParam(param.getErpParam()));
						sub.put(param.getKdParam(), date);
					}else if (param.getType() == DataType.BASEINFO.getCode()) {
						Map<String, Object> base = new HashMap<String, Object>();
						base.put("number", item.getValueByParam(param.getErpParam()));
						sub.put(param.getKdParam(), base);
					} else {
						sub.put(param.getKdParam(), item.getValueByParam(param.getErpParam()));
					}
				} else {
					if (param.getType() == DataType.NUMBER.getCode()) {
						sub.put(param.getKdParam(), new BigDecimal(param.getDefaultValue()));
					}else if (param.getType() == DataType.BASEINFO.getCode()) {
						Map<String, Object> base = new HashMap<String, Object>();
						base.put("number", param.getDefaultValue());
						sub.put(param.getKdParam(), base);
					} else {
						sub.put(param.getKdParam(), param.getDefaultValue());
					}
				}
			}
			subs.add(sub);
		}
		log.debug("+++++++++++++"+JSONObject.toJSONString(subs).toString());
		mainData.put("entry", subs);
		data.add(mainData);
		return JSONArray.toJSONString(data);
	}

	public String dateFormat(String date) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", java.util.Locale.US);
			Date dd = format.parse(date);
			SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format2.format(dd);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
